package com.mango.game.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mango.game.common.JwtTokenProvider;
import com.mango.game.common.RequestContextHolder;
import com.mango.game.dtos.RequestContextDTO;
import com.mango.game.dtos.ResponseDTO;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");

        if (token == null || StringUtils.isEmpty(token)) {
            response(request, response, 403, "权限不足，需要登录");
            return false;
        }
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        Claims claims = jwtTokenProvider.getClaimsFromToken(token);
        if (claims == null) {
            response(request, response, 403, "授权错误，密钥错误");
            return false;
        }
        try {
            RequestContextDTO dto = new RequestContextDTO();
            dto.setUserName(claims.getSubject());
            dto.setNameSpace(claims.get("name_space", Long.class));
            dto.setGameId(claims.get("game_id", Long.class));
            dto.setChannelId(claims.get("channel_id", Long.class));
            dto.setProductsId(claims.get("products_id", Long.class));
            dto.setUserId(claims.get("user_id", Long.class));
            RequestContextHolder.setRequestContext(dto);    // 保存登录信息
        } catch (Exception e) {
            response(request, response, 403, "授权错误，数据错误");
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestContextHolder.clear();   // 请求完成后清理 ThreadLocal
    }

    private void response(HttpServletRequest request, HttpServletResponse response, Integer status, String message) throws IOException {
        String body = objectMapper.writeValueAsString(new ResponseDTO(status, message));

        request.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");

        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(status);
        response.getWriter().println(body);
        response.flushBuffer();
    }
}
